package com.hfut.manage.controller;


import com.hfut.manage.pojo.Family;
import com.hfut.manage.pojo.Result;
import com.hfut.manage.pojo.Teacher;
import com.hfut.manage.service.IFamilyService;
import com.hfut.manage.service.impl.FamilyServiceImpl;
import com.hfut.manage.service.impl.TeacherServiceImpl;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.util.List;
import java.util.stream.Collectors;

@RestController
@RequestMapping("/family")
public class FamilyController {

    @Autowired
    private FamilyServiceImpl familyService;

    @Autowired
    private TeacherServiceImpl teacherService;

    @GetMapping
    public Result list() {
        List<Family> familyList = familyService.list();
        return Result.success(familyList);
    }

    @GetMapping("/id")
    public Result list(@RequestParam(defaultValue = "id") Integer id) {
        List<Family> familyList = familyService.lambdaQuery()
                .like(Family::getId, id)
                .list();
        return Result.success(familyList);
    }

    @GetMapping("/teacherId/{teacherid}")
    public Result getByTeacherId(@PathVariable("teacherid") Long teacherId) {
        List<Family> familyList = familyService.lambdaQuery()
                .eq(Family::getTeacherId, teacherId)
                .list();
        return Result.success(familyList);
    }

    @GetMapping("/teacherName/{teachername}")
    public Result getByTeacherName(@PathVariable("teachername") String teacherName) {
        List<Teacher> teacherList = teacherService.lambdaQuery().eq(Teacher::getName,teacherName).list();
        List<Integer> teacherIds = teacherList.stream()
                .map(Teacher::getId)
                .collect(Collectors.toList());

        List<Family> familyList = familyService.lambdaQuery()
                .in(Family::getTeacherId, teacherIds)
                .list();

        return Result.success(familyList);
    }

    @PostMapping
    public Result save(@RequestBody Family family) {

        List<Family> familyList = familyService.lambdaQuery().eq(Family::getTeacherId, family.getTeacherId()).list();
        if(familyList.size()>0){
            return Result.error(500, "新增家庭失败,教师已有家庭");
        }
        boolean success = familyService.saveFamily(family);
        if (!success) {
            return Result.error(500, "新增家庭失败");
        }
        return Result.success();
    }


    @PutMapping
    public Result put(@RequestBody Family family) {
        boolean suceess = familyService.updateById(family);
        if (!suceess) {
            return Result.error(500, "更新失败");
        }
        return Result.success();
    }



    @DeleteMapping("/{id}")
    public Result del(@PathVariable("id") Long id) {
        boolean success = familyService.deleteFamily(id);
        if (!success) {
            return Result.error(500, "删除家庭失败");
        }
        return Result.success();
    }

}
